﻿using MikuMikuLibrary.Databases;
using MikuMikuLibrary.IO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DatabaseConverter
{
    class MotMerge
    {
        public MotionDatabase db = new MotionDatabase();
        public MotionDatabase db2 = new MotionDatabase();
        public List<int> ids = new List<int>();
        public List<int> ids2 = new List<int>();

        public void MergeAet()
        {
            int MaxId = 0;
            foreach (var i in db.MotionSets)
            {
                if (i.Id > MaxId)
                {
                    MaxId = i.Id;
                    ids.Add(i.Id);
                }
            }

            foreach (var i in db2.MotionSets)
            {
                var stringcheck = db.MotionSets.Where(c => c.Name == i.Name).FirstOrDefault();
                if (stringcheck == null)
                {
                    foreach (var u in i.Motions)
                    {
                        var result2 = ids.Where(c => c == u.Id).FirstOrDefault();
                        if (result2 == u.Id)
                        {
                            var maxids = ids.Max() + 1;
                            while (result2 == u.Id)
                            {
                                result2 = ids.Where(c => c == maxids).FirstOrDefault();
                                if (result2 == u.Id) maxids++;
                            }
                            u.Id = (ushort)maxids;
                        }
                        ids.Add(u.Id);
                    }
                    var result = db.MotionSets.Where(c => c.Id == i.Id).FirstOrDefault();
                    if (result == null)
                    {
                        db.MotionSets.Add(i);
                    }
                    else
                    {
                        result = db.MotionSets.Where(c => c.Id == (ushort)(MaxId + 1)).FirstOrDefault();
                        while (result != null)
                        {
                            MaxId++;
                            result = db.MotionSets.Where(c => c.Id == (ushort)(MaxId + 1)).FirstOrDefault();
                        }
                        i.Id = (ushort)(MaxId + 1);
                        db.MotionSets.Add(i);
                    }
                }
            }
        }
    }
}
